package com.jxust.vhremployee9092.controller;

import com.jxust.debate.feign.AdminService;
import com.jxust.debate.feign.RedisService;
import com.jxust.debate.pojo.Department;
import com.jxust.debate.pojo.Employee;
import com.jxust.debate.pojo.PicUploadResult;
import com.jxust.debate.util.CommonResult;
import com.jxust.debate.util.PageInfo;
import com.jxust.debate.util.VerifyCodeUtil;
import com.jxust.vhremployee9092.security.util.JavaWebToken;
import com.jxust.vhremployee9092.service.DepartmentService;
import com.jxust.vhremployee9092.service.PictureUploadService;
import com.jxust.vhremployee9092.service.TestService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.jxust.debate.util.VerifyCodeUtil.generateImageCode;

/**
 * // 需要有system权限才能访问
 * @RequiresPermissions("system")
 *
 * // 需要有system和front权限才能访问,logical可以不写,默认是AND
 * @RequiresPermissions(value={"system","front"}, logical=Logical.AND)
 *
 * // 需要有system或front权限才能访问
 * @RequiresPermissions(value={"system","front"}, logical=Logical.OR)
 *
 * // 需要有admin或user角色才能访问
 * @RequiresRoles(value={"admin","user"}, logical=Logical.OR)
 * @author tyeerth
 * @date 2020/12/26 - 19:45
 */
@RestController
@RequestMapping("/employee")
@Slf4j
@Api(value="员工controller",tags={"员工操作接口"})
public class testhandler {
    //远端调用AdminService的服务
    @Resource
    private AdminService adminService;

    @Resource
    private TestService testService;

    @Resource
    private DepartmentService departmentService;

    @Resource
    private RedisService redisService;

    @Resource
    private PictureUploadService picUploadService;


    @ApiOperation("员工注册")
    @PostMapping("/register")
    public CommonResult<String> register(@RequestParam(value="username")@ApiParam(name = "username",value = "用户名不能为空") String username,
                                         @RequestParam(value="password")@ApiParam(name = "password",value = "密码不能为空") String password){
        return testService.registerEmployee(username,password);
    }

    @GetMapping("/verifyCode")
    @ApiOperation(value = "获取图片验证码")
    public CommonResult<String> verifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        /*禁止缓存*/
        response.setDateHeader("Expires",0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        /*获取验证码*/
        String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_ALL_MIXED,4,null);
        /*验证码已key，value的形式缓存到redis 存放时间一分钟*/
        log.info("验证码============>" + verifyCode);
        String uuid = UUID.randomUUID().toString();
        redisService.setRedisKeyValueRemoteWithTimeout(uuid,verifyCode,1, TimeUnit.MINUTES);
        //bufferedImage 是生成的图片
        BufferedImage bufferedImage = generateImageCode(verifyCode, 90, 30, 10, true, Color.WHITE, Color.BLACK, null);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        //参数内容为图片，图片后缀，流
        ImageIO.write(bufferedImage, "jpg", stream);
        byte[] bytes = stream.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        //转换成base64串
        String png_base64 = encoder.encodeBuffer(bytes).trim();
        //删除 \r\n
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");
        //返回的字符串头要拼接data:image/jpg;base64,在字符串前面，这样前台就可以直接在img的src里面直接使用该字符串
//        redisTemplate.opsForValue().set(uuid,code,1,TimeUnit.MINUTES);
        Cookie cookie = new Cookie("captcha",uuid);
        /*key写入cookie，验证时获取*/
        response.addCookie(cookie);
        return CommonResult.success("验证码返回成功","data:image/jpg;base64,"+png_base64);
    }

//    @RequestMapping("pic/upload")
    @ApiOperation(value = "上传图片")
    @PostMapping("pic/upload")
    @ResponseBody
    public PicUploadResult upload(@RequestParam("file") @ApiParam(name = "file",value = "file") MultipartFile multipartFile) {
        return this.picUploadService.upload(multipartFile);
    }

    @ApiOperation(value = "获取当前员工的个人信息")
    @PostMapping("/getEmployeeInfo")
    public CommonResult hello(HttpServletRequest request){
        String authHeader = request.getHeader("Authorization");
        final String authToken = authHeader.substring("Bearer ".length());
        Map<String, Object> stringObjectMap = JavaWebToken.parserJavaWebToken(authToken);
        String username = (String) stringObjectMap.get("userId");
        log.info("当前用户名为{}",username);
        Employee employee = new Employee();
        employee.setUsername(username);
        return testService.getEmployeeByUsername(employee);
    }

    @ApiOperation(value = "计算+", notes = "加法")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "a", paramType = "path", value = "数字a", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "b", paramType = "path", value = "数字b", required = true, dataType = "Long")
    })
    @GetMapping("/{a}/{b}")
    public Integer get(@PathVariable Integer a, @PathVariable Integer b) {
        return a + b;
    }

    @ApiOperation(value = "完善当前登入员工的其它信息")
    @PostMapping("/insertEmployee")
    public CommonResult<String> insertEmployee(@RequestBody @ApiParam(name="用户对象",value="传入json格式") Employee employee,HttpServletRequest request){
        String authHeader = request.getHeader("Authorization");
        final String authToken = authHeader.substring("Bearer ".length());
        Map<String, Object> stringObjectMap = JavaWebToken.parserJavaWebToken(authToken);
        String username = (String) stringObjectMap.get("userId");
        Employee employee1 = testService.getEmployee(username);
        employee.setId(employee1.getId());
        return testService.insertEmployee(employee);
    }
    @ApiOperation(value = "修改当前登入员工的信息")
    @PostMapping("/updateEmployee")
    public CommonResult<String> updateEmployee(@RequestBody @ApiParam(name="用户对象",value="传入json格式") Employee employee,HttpServletRequest request){
        String authHeader = request.getHeader("Authorization");
        final String authToken = authHeader.substring("Bearer ".length());
        Map<String, Object> stringObjectMap = JavaWebToken.parserJavaWebToken(authToken);
        String username = (String) stringObjectMap.get("userId");
        Employee employee1 = testService.getEmployee(username);
        employee.setId(employee1.getId());
        return testService.insertEmployee(employee);
    }
    @ApiOperation(value = "分页查询所有员工信息")
    @GetMapping("/getAll")
    public CommonResult<PageInfo<Employee>> getAll(
            @RequestParam (value="pageNum", defaultValue="1") @ApiParam(name = "pageNum",value = "默认值为1") Integer pageNum,
            // pageSize默认值使用5
            @RequestParam(value="pageSize", defaultValue="10")@ApiParam(name = "pageSize",value = "默认值为10") Integer pageSize
    ){
        PageInfo<Employee> all = testService.getAll(new Employee(),pageNum, pageSize);
        return CommonResult.success("查找成功",all);
    }

    @ApiOperation("根据username获取用户信息")
    @PostMapping("/getEmployeeByUsername")
    public CommonResult<Employee> getEmployeeByUsername(@RequestBody @ApiParam(name="username",value="用户名") Employee employee){
        return testService.getEmployeeByUsername(employee);
    }
    @ApiOperation("获取所有的部门信息")
    @PostMapping("/getAllDepartment")
    public CommonResult<List<Department>> getAllDepartment(){
        return departmentService.getAllDepartment();
    }
}
